package com.entrogy.service.impl;

import com.entrogy.bean.*;
import com.entrogy.dao.*;
import com.entrogy.service.FinalNoticeService;
import com.entrogy.utils.SendUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @ClassName FinalNoticeServiceImpl
 * @Description
 * @Author luoxingjiang
 * @Date 2019-12-18 上午 10:13
 * @Version 1.0
 **/
@Service
@Transactional
public class FinalNoticeServiceImpl implements FinalNoticeService {

    @Autowired
    private FinalNoticeMapper finalNoticeMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private ParentMapper parentMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private ClassMapper classMapper;

    private static final Logger logger = LoggerFactory.getLogger(FinalNoticeServiceImpl.class);


    @Override
    public List<FinalNoticeCommentTemplateEntity> listComment(Integer schoolCode, Integer finalNoticeCommentId, String uid) {
        return finalNoticeMapper.listComment(schoolCode, finalNoticeCommentId, uid);
    }

    @Override
    public FinalNoticeEntity getFinalNotice(Integer finalNoticeId, Integer schoolCode) {
        FinalNoticeEntity finalNotice = finalNoticeMapper.getFinalNotice(finalNoticeId);
        // 查询通知书内容
        finalNotice.setFinalNoticeContent(finalNoticeMapper.listFinalNoticeContent(null, finalNotice.getFinalNoticeContentId(), null, null, null, null).get(0));
        // 查询该通知书对应的学生信息
        StudentBasicInfoEntity student = studentMapper.listStudent(null, null, null, finalNotice.getStudentId(), null).get(0);
        student.setFinalNoticeTeacherComment(finalNotice.getFinalNoticeTeacherCommentId() == null ? null : finalNoticeMapper.getStudentComment(null, null, null, finalNotice.getFinalNoticeTeacherCommentId()));
        finalNotice.setStudent(student).setSchoolName(schoolMapper.getSchoolName(schoolCode));
        return finalNotice;
    }

    @Override
    public boolean insertStudentEvaluate(List<FinalNoticeTeacherCommentEntity> teacherCommentList, Integer schoolCode) {
        Iterator iterator = teacherCommentList.iterator();
        while (iterator.hasNext()){
            FinalNoticeTeacherCommentEntity next = (FinalNoticeTeacherCommentEntity) iterator.next();
            if (next.getId() != null) {
                // 有id就是修改
                int updateStudentTeacherCommentRow = finalNoticeMapper.updateStudentTeacherComment(next.getId(), next.getFinalNoticeCommentTemplate().getId());
                iterator.remove();
            }
        }
        if (teacherCommentList.size() > 0){
            for (FinalNoticeTeacherCommentEntity teacherComment : teacherCommentList) {
                int insertStudentTeacherComment = finalNoticeMapper.insertStudentTeacherComment(teacherComment);
                // 首先查询该生该学年该学期是否已经生成通知书，已经生成才去更新通知书的评语id
                List<Integer> studentIdList = new ArrayList<>();
                studentIdList.add(teacherComment.getStudentId());
                List<StudentBasicInfoEntity> studentList = finalNoticeMapper.listStudentForFinalNotice(schoolCode, null, teacherComment.getTerm(), teacherComment.getTermOfYear(), null, studentIdList);
                if (studentList.size() > 0){
                    // 新增要更新该学年该学期该学生的通知书评语id
                    FinalNoticeEntity finalNotice = new FinalNoticeEntity();
                    finalNotice.setTerm(teacherComment.getTerm()).setTermOfYear(teacherComment.getTermOfYear())
                            .setStudentId(teacherComment.getStudentId())
                            .setFinalNoticeTeacherCommentId(teacherComment.getId());
                    int updateStudentFinalNoticeRow = finalNoticeMapper.updateStudentFinalNotice(finalNotice);
                }
            }
        }
        return true;
    }

    @Override
    public boolean updateStudentFinalNotice(FinalNoticeEntity finalNotice) {
        return finalNoticeMapper.updateStudentFinalNotice(finalNotice) > 0;
    }

    @Override
    public List<StudentBasicInfoEntity> listStudentForEvaluate(String uid, String term, String termOfYear) {
        UserEntity teacher = userMapper.getUserByUid(uid);
        List<StudentBasicInfoEntity> studentList = studentMapper.listStudent(teacher.getSchoolCode(), Integer.valueOf(teacher.getGradeId()), Integer.valueOf(teacher.getClassId()), null, null);
        for (StudentBasicInfoEntity student : studentList) {
            Integer studentId = student.getId();
            // 判断这名学生的评语状态
            FinalNoticeTeacherCommentEntity finalNoticeTeacherComment = finalNoticeMapper.getStudentComment(studentId, term, termOfYear, null);
            student.setFinalNoticeTeacherComment(finalNoticeTeacherComment);
        }
        return studentList;
    }

    @Override
    public List<StudentBasicInfoEntity> listStudentForFinalNotice(Integer schoolCode, Integer gradeId, String term, String termOfYear, String studentName, List<Integer> studentIdList) {
        return finalNoticeMapper.listStudentForFinalNotice(schoolCode, gradeId, term, termOfYear, studentName, studentIdList);
    }

    @Override
    public List<FinalNoticeContentEntity> listFinalNoticeContent(Integer schoolCode, String term, String termOfYear, Integer gradeId, Integer deleteStatus) {
        return finalNoticeMapper.listFinalNoticeContent(schoolCode, null, term, termOfYear, gradeId, deleteStatus);
    }

    @Override
    public boolean generateFinalNotice(String uid, String term, String termOfYear, Integer gradeId, Integer examId, Integer finalNoticeContentId, Integer override) {
        Integer schoolCode = userMapper.getSchoolCodeByUserId(uid);
        // 首先统计是否已经生成过该学年该学期该年级的通知书
        Integer totalCount = finalNoticeMapper.countFinalNotice(term, termOfYear, gradeId, schoolCode);

        // 判断是否覆盖，需要覆盖的话，删除该学年该学期该年级的通知书记录
        if (override == 1){
            logger.info("用户=>{}正在进行通知书覆盖操作！term=>{};termOfYear=>{};gradeId=>{}", uid, term, termOfYear, gradeId);
            int deleteFinalNoticeRow = finalNoticeMapper.deleteFinalNotice(term, termOfYear, gradeId, schoolCode);
        }

        // 生成通知书要注意的是可能有某些学生的老师还未评价，所以先将所有学生的评语记录查询出来后插入通知书记录，等老师评论后再更新这条通知书记录
        // 查询学生列表（附带评语信息）
        List<StudentBasicInfoEntity> studentList = finalNoticeMapper.listStudent(schoolCode, gradeId, null, null, null);
        List<FinalNoticeEntity> finalNoticeList = new ArrayList<>();
        for (StudentBasicInfoEntity student : studentList) {
            FinalNoticeTeacherCommentEntity finalNoticeTeacherComment = student.getFinalNoticeTeacherComment();
            // 组装通知书
            FinalNoticeEntity finalNotice = new FinalNoticeEntity();
            finalNotice.setFinalNoticeContentId(finalNoticeContentId)
                    .setTermOfYear(termOfYear).setTerm(term).setCreateUserId(uid)
                    .setExamId(examId).setStudentId(student.getId())
                    .setFinalNoticeTeacherCommentId(finalNoticeTeacherComment == null ? null : finalNoticeTeacherComment.getId());
            finalNoticeList.add(finalNotice);
         }
        if (finalNoticeList.size() > 0){
            int insertRow = finalNoticeMapper.insertStudentFinalNotice(finalNoticeList);
        }

        // 第一次生成的话需要通知给家长
        // 该校是否处于试运行状态
        Integer openStatus = schoolMapper.getSchoolOpenStatus(schoolCode);
        if(totalCount == 0){
            // 查询发送了通知书的学生
            List<StudentBasicInfoEntity> studentSendList = finalNoticeMapper.listStudentForFinalNotice(schoolCode, gradeId, term, termOfYear, null, null);
            for (StudentBasicInfoEntity student : studentSendList) {
                List<ParentVisitorEntity> studentParentList = parentMapper.listParentByStudentId(student.getId());
                for (ParentVisitorEntity parentVisitorEntity : studentParentList) {
                    // 判断该学生是否开通通知服务，暂时不判断
//                    if (openStatus == 0){
//                        boolean studentIsPay = studentMapper.getStudentPayStatus(student.getId()) != null;
//                        if (!studentIsPay){
//                            logger.info("学生=>" + student.getStudentName() + "未付费，此次期末通知书通知将不会发送给家长=>" + parentVisitorEntity.getParentVisitorName());
//                            continue;
//                        }
//                    }
                    PubCountEntity pubCountEntity = messageMapper.getPubCountOpenidByPhone(parentVisitorEntity.getParentVisitorPhone());
                    if (null != pubCountEntity && StringUtils.isNoneBlank(pubCountEntity.getOpenid())){
                        String schoolName = schoolMapper.getSchoolName(schoolCode);
                        String gradeName = classMapper.getClassById(gradeId, schoolCode).getClassName();
                        String content = "《" + schoolName +"》" + "发布了《" + termOfYear + "学年" + term + "学期》" + gradeName + "的期末通知书，请打开《脸卡通》小程序查看！";
                        LocalDateTime sendTime = LocalDateTime.now();
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        logger.info("期末通知书通知发送，内容：{}，家长openId：{}，发送时间：{}", content, pubCountEntity.getOpenid(), sendTime.format(formatter));
                        String[] paramsWeiXin = { "",  schoolName, schoolName, sendTime.format(formatter), content, ""};
                        // path参数为点击公众号消息后跳转的地址
                        SendUtils.sendByWeixinAndPath(pubCountEntity, paramsWeiXin, pubCountEntity.getTemplateId(), "packageA/pages/letter/letter");
                    }
                }
            }
        }

        return true;
    }

    @Override
    public boolean deleteFinalNoticeContent(Integer finalNoticeContentId) {
        // 软删除
        Integer deleteStatus = 1;
        FinalNoticeContentEntity finalNoticeContent = new FinalNoticeContentEntity();
        finalNoticeContent.setId(finalNoticeContentId).setDeleteStatus(deleteStatus);
        return finalNoticeMapper.updateFinalNoticeContent(finalNoticeContent) > 0;
    }

    @Override
    public boolean updateFinalNoticeContent(FinalNoticeContentEntity finalNoticeContent) {
        return finalNoticeMapper.updateFinalNoticeContent(finalNoticeContent) > 0;
    }

    @Override
    public boolean insertFinalNoticeContent(FinalNoticeContentEntity finalNoticeContent) {
        Integer schoolCode = userMapper.getSchoolCodeByUserId(finalNoticeContent.getCreateUserId());
        finalNoticeContent.setSchoolCode(schoolCode);
        return finalNoticeMapper.insertFinalNoticeContent(finalNoticeContent) > 0;
    }

    @Override
    public Integer countFinalNotice(String term, String termOfYear, Integer gradeId, Integer schoolCode) {
        return finalNoticeMapper.countFinalNotice(term, termOfYear, gradeId, schoolCode);
    }

    @Override
    public List<StudentScoreEntity> listStudentFinalExamScore(Integer examId, Integer gradeId, String scoreTableName) {
        return finalNoticeMapper.listStudentFinalExamScore(examId, gradeId, scoreTableName);
    }

    @Override
    public Integer insertComment(FinalNoticeCommentTemplateEntity finalNoticeCommentTemplate) {
        Integer insertRow = finalNoticeMapper.insertComment(finalNoticeCommentTemplate);
        return finalNoticeCommentTemplate.getId();
    }
}
